package com.konjac.service.impl;

import com.konjac.dao.mapper.UserMapper;
import com.konjac.pojo.ServiceState;
import com.konjac.pojo.User;
import com.konjac.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class UserServiceImpl implements UserService {
    //用户/管理员登录
    public ServiceState signIn(String username, String password) throws IOException {
        //加载mybaits核心配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //测试数据

        User user = new User();
        ServiceState serviceState = new ServiceState();

        //空值检查
        if (username == "" || username == null || password == "" || password == null) {
            serviceState.setFlag(0);
            serviceState.setMsg("登录失败! 用户名和密码不能为空!");
            System.out.println(serviceState.getMsg() + " " + serviceState.getFlag());
            return serviceState;
        }

        try {
            user = userMapper.selectByUsername(username);
            //用户名密码匹配检查
            if (password.equals(user.getPassword())) {
                serviceState.setFlag(1);
                serviceState.setMsg("登录成功! ");
            } else {
                serviceState.setFlag(0);
                serviceState.setMsg("登录失败! 请检查用户名和密码是否正确!");
                //System.out.println(serviceState.getMsg() + " " + serviceState.getFlag());
                return serviceState;
            }
            //权限检查
            if (user.getUserPower().equals(1)) {
                serviceState.setMsg(serviceState.getMsg() + "您的身份是: 管理员. ");
                serviceState.setPs("admin");
            } else {
                serviceState.setMsg(serviceState.getMsg() + "您的身份是: 顾客. ");
                serviceState.setPs("customer");
            }
        } catch (Exception e) {
            e.printStackTrace();
            serviceState.setFlag(0);
            serviceState.setMsg("登录失败! 用户名不存在!");
            //System.out.println(serviceState.getMsg() + " " + serviceState.getFlag());
            return serviceState;
        } finally {
        }

        sqlSession.close();
        //System.out.println(serviceState.getMsg() + " " + serviceState.getFlag());
        //向controller返回判断结果和权限
        return serviceState;

    }
}
